package cn.faifai.desktop.view.dialog;

import cn.faifai.desktop.api.FileUrlController;
import cn.faifai.desktop.api.TagController;
import cn.faifai.desktop.events.FileSecondaryClickEvent;
import cn.faifai.desktop.events.ShowFileTaggingDialogEvent;
import cn.faifai.common.utils.SpringContextUtil;
import cn.faifai.desktop.events.TagClearEvent;
import cn.faifai.desktop.viewModel.TagViewModel;
import cn.faifai.framework.utils.SingleEvenBus;
import cn.faifai.tagapi.dto.FileUrlDto;
import cn.faifai.tagapi.dto.PageQuery;
import cn.faifai.tagapi.dto.TagDTO;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javafx.beans.binding.Bindings;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class FileTaggingDialog {

    @Getter
    private BorderPane layout;
    private String selectedFilePath;
    private TagViewModel tagViewModel = new TagViewModel();
    private TextField searchField;
    private Button searchButton;
    private ListView<TagDTO> searchResultListView;
    private ListView<TagDTO> selectedTagListView;
    private Button submitButton;
    private Stage stage;

    // 单例模式
    private static class SingletonHolder {
        private static final FileTaggingDialog INSTANCE = new FileTaggingDialog();
    }

    public static FileTaggingDialog getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private FileTaggingDialog(){}

    public BorderPane init() {
        // 注册事件监听器
        searchResultListView = initSearchResultListView();
        selectedTagListView = initSelectedTagListView();
        submitButton = initSubmitButton();
        layout = new BorderPane();
        searchField = initSearchField();
        searchButton = initSearchButton();

        // 创建顶部HBox并设置其内部组件居中对齐
        HBox topHBox = new HBox(searchField, searchButton);
        topHBox.setAlignment(Pos.CENTER); // 设置为居中对齐

        // 创建底部HBox并设置其内部组件居中对齐
        HBox bottomHBox = new HBox(submitButton);
        bottomHBox.setAlignment(Pos.CENTER); // 设置为居中对齐

        // 创建用于平分中心区域的HBox
        HBox centerHBox = new HBox();
        centerHBox.setPadding(new Insets(10));

        // 设置VBox作为左右两侧的内容容器
        VBox leftVBox = new VBox(searchResultListView);
        VBox rightVBox = new VBox(selectedTagListView);

        // 使用Region作为占位符以平衡空间
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS); // 使得spacer能够扩展并占据可用空间

        // 将leftVBox、spacer和rightVBox添加到centerHBox中
        centerHBox.getChildren().addAll(leftVBox, spacer, rightVBox);

        layout.setTop(topHBox);
        layout.setCenter(centerHBox);
        layout.setBottom(bottomHBox);
        layout.setPadding(new Insets(1));

        return layout;
    }

    // 设置搜索按钮
    private Button initSearchButton() {
        Button searchButton = new Button("搜索");
        searchButton.setOnAction(event -> {
            log.info("搜索值："+tagViewModel.getName());
            TagController tagController = SpringContextUtil.getContext().getBean(TagController.class);
            PageQuery pageQuery = new PageQuery(1, 10);
            List<TagDTO> searchList = tagController.getTagDTOPageList(tagViewModel.toTagDTO(), pageQuery).getRows();
            searchResultListView.getItems().clear();
            searchResultListView.getItems().addAll(searchList);

        });
        return searchButton;
    }

    // 设置搜索框
    private TextField initSearchField() {
        TextField searchField = new TextField();
        Bindings.bindBidirectional(searchField.textProperty(), tagViewModel.nameProperty());
        searchField.setPromptText("输入标签搜索...");
        return searchField;
    }

    // 初始化搜索展示列表
    private ListView<TagDTO> initSearchResultListView() {
        ListView<TagDTO> tagDTOListView = new ListView<>();
        tagDTOListView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                TagDTO selectedItem = tagDTOListView.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    Set<TagDTO> selectItemSet = selectedTagListView.getItems().stream().collect(Collectors.toSet());
                    selectItemSet.add(selectedItem);
                    selectedTagListView.getItems().clear();
                    selectedTagListView.getItems().addAll(selectItemSet);
                }
            }
        });
        return tagDTOListView;
    }

    // 初始化选中标签列表
    private ListView<TagDTO> initSelectedTagListView() {
        ListView<TagDTO> tagDTOListView = new ListView<>();
        tagDTOListView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                TagDTO selectedItem = tagDTOListView.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    selectedTagListView.getItems().remove(selectedItem);
                }
            }
        });
        FileUrlController fileUrlController = SpringContextUtil.getContext().getBean(FileUrlController.class);
        List<TagDTO> tagDTOS = fileUrlController.getFileTags(selectedFilePath);
        if (tagDTOS != null){
            tagDTOListView.setItems(FXCollections.observableList(tagDTOS));
        }
        return tagDTOListView;
    }

    // 初始化提交按钮
    private Button initSubmitButton() {
        Button submitButton = new Button("提交");
        submitButton.setOnAction(event -> {
            // 获取选中的标签
            List<TagDTO> selectedTags = selectedTagListView.getItems();
            // 获取文件路径
            String filePath = selectedFilePath;
            // 提交标签到文件
            // ...
            FileUrlController fileUrlController = SpringContextUtil.getContext().getBean(FileUrlController.class);
            try {
                Boolean updateFlag = fileUrlController.replaceTag(new FileUrlDto(null, filePath, selectedTags.stream().map(TagDTO::getId).collect(Collectors.toList())));
                if (updateFlag){
                    stage.close();
                    if (CollectionUtil.isEmpty(selectedTags)) {
                        SingleEvenBus.getInstance().post(new TagClearEvent());
                    }
                    log.info("标签关联成功");
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("成功");
                    alert.setHeaderText(null);
                    alert.setContentText("标签关联成功");
                    alert.showAndWait();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
            // 关闭窗口
        });
        return submitButton;
    }


    @Subscribe
    public void handleFileTagEvent(FileSecondaryClickEvent event) {
        Platform.runLater(() -> {
            System.out.println("收到文件标签事件: 文件名=" + event.getFilePath() + ", 标签=" + event.getTagId());
            selectedFilePath = event.getFilePath();
        });
    }

    @Subscribe
    public void handleShowFileTaggingDialogEvent(ShowFileTaggingDialogEvent event) {
        Platform.runLater(() -> {
            if (stage != null) stage.close();
            stage = new Stage();
            stage.setScene(new Scene(init(), 300, 250));
            stage.setTitle("标签关联：" + selectedFilePath);
            stage.show();
        });
    }
}